<template>
  <div class="order-admin">
    <div class="switch-add" @click="handleExchange">
      <span class="uname"
        >就诊人：{{usernamer}}
        <van-button type="primary" size="mini" plain>切换</van-button></span
      >
    </div>

    <van-tabs v-model="active" color="#4ECE40" @change="handleChange">
      <van-tab
        v-for="(item, index) in tabList"
        :key="index"
        :title="item.label"
        :name="item.value"
      ></van-tab>
    </van-tabs>

    <div class="order-container" v-if="orderList.length > 0">
      <van-panel v-for="(item, index) in orderList" :key="index">
        <template #header>
          <van-cell
            @click="handleDetail(item)"
            :title="item.organ_name"
            :icon="`${staticPath}/logo@2x.png`"
            :value="item.order_status | orderStatus"
            :class="`status-${item.order_status}`"
          />
        </template>
        <div class="order-product" @click="handleDetail(item)">
          <div class="order-product-hd">
            <img :src="item.goods_picurl" alt="" />
          </div>
          <div class="order-product-bd">
            <h2>
              {{ item.goods_name }}
            </h2>
            <div class="order-text">
              <span class="order-text-hd price"
                >￥{{ item.total_amount }}
              </span>
            </div>
          </div>
        </div>
        <template #footer>
          <div style="display: flex; justify-content: flex-end">
            <van-button size="small" round v-if="item.order_status == 9" @click="handleCancel(item,'13')"
              >确认完成</van-button
            >
            <van-button
              size="small"
              round
              v-if="item.order_status == 1"
              @click="handleCancel(item,'7')"
              >取消订单</van-button
            >
            <van-button
              size="small"
              color="#4ECE40"
              plain
              round
              v-if="item.order_status == 1"
              @click="handlePayMent(item)"
              >立即付款</van-button
            >
            <van-button size="small" round v-if="item.order_status == 13" :to="`/user/order/comment/${item.order_id}?goods_id=${item.goods_id}&is_evaluate=${item.is_evaluate}`"
              >{{item.is_evaluate == 1 ? '评价晒图' : '查看评价'}}</van-button
            >
            <van-button size="small" @click="$router.push({path: `/huli/detail/${item.goods_id}`})" round v-if="item.order_status == 13 || item.order_status == 7"
              >再次购买</van-button
            >
          </div>
        </template>
      </van-panel>
      <div class="pagination">
        <van-pagination
          v-model="currentPage"
          @change="handlePage"
          :page-count="pageCount"
          mode="simple"
          :items-per-page="20"
        />
      </div>
    </div>

    <van-empty description="暂无数据" v-else />

    <van-dialog v-model="show" title="选择就诊人" show-cancel-button @confirm="handleConfirm" theme="round-button">
      <div class="min-wrapper">
        <van-radio-group v-model="radio" @change="handleRadio">
          <van-radio :name="item.id" v-for="(item,index) in memberArrList" :key="index" checked-color="#4ECE40">{{item.name}}</van-radio>
        </van-radio-group>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import {
  ucenterOrderOption,
  ucenterOrder,
  ucenterOrderCancel,
} from "@/service/order";
import { memberList,memberDefaultService,nurseItemOrderServer,nurseOrderPayment } from "@/service/server";
export default {
  data() {
    return {
      active: "",
      radio: localStorage.getItem('userId') || '',
      show: false,
      tabList: [],
      currentPage: 1,
      pageCount: 0,
      orderList: [],
      stateList: [],
      memberArrList: [],
      memberDefault:{},
      usernamer: localStorage.getItem('usernamer') || '',
      staticPath: process.env.VUE_APP_STATIC_PATH
    };
  },

  created() {
    this.queryOption();
    let user_id = localStorage.getItem('userId')
    if(!user_id){
      this.queryMemberDefault();
    }else{
      this.radio = Number(user_id)
      this.queryOrderList({
        order_state: this.active,
        user_people_id: user_id,
        currentPage: this.currentPage
      })
    }
    console.log(this.$route);
    if (Object.keys(this.$route.query).length) {
      console.log(this.$route.query.active);
      this.$nextTick(() => {
        this.active = Number(this.$route.query.active);
      });
      
    } else {
      
    }
    
    this.queryMemberList();
  },

  components: {},

  computed: {},

  methods: {
    async handlePayMent(item){
      let { user_id,username,province,city,district,address,mobile,call_time,user_note,goods_id,goods_name,order_amount,order_id,order_sn,user_people_id,consignee } = item;
      let form = {
        user_people_id,
        consignee,
        province,
        city,
        district,
        address,
        mobile,
        call_time,
        user_note,
        goods_name,
        goods_id,
        order_amount,
        order_id,
        order_sn
      }
      let params = Object.assign({},form);

       let result = await nurseOrderPayment(params);
       if(result.status == 200){
        
         let order_id = result.data.order_id;

         let payment = result.data;
         console.log();
        //let payment = await nurseOrderPayment({
         // order_id
        //});
        if (typeof WeixinJSBridge == "undefined") {
          if (document.addEventListener) {
            document.addEventListener(
              "WeixinJSBridgeReady",
              this.onBridgeReady(parament),
              false
            );
          } else if (document.attachEvent) {
            document.attachEvent("WeixinJSBridgeReady", this.onBridgeReady(payment));
            document.attachEvent("onWeixinJSBridgeReady", this.onBridgeReady(payment));
          }
        }else{
          this.onBridgeReady(payment);
        }
       }else{
         this.$toast("参数错误：");
       }
    },
    onBridgeReady(json) {
      let that = this;
      console.log(json);
      WeixinJSBridge.invoke("getBrandWCPayRequest", json, function (res) {
        // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回 ok，但并不保证它绝对可靠。
        if (res.err_msg == "get_brand_wcpay_request:ok") {
          that.queryOrderList({
              order_state: that.active,
              user_people_id: that.radio,
              currentPage: that.currentPage
            });
        } else {
          that.$toast("支付失败，请联系客服...");
        }
      });
    },
    async queryMemberDefault(){
      let result = await memberDefaultService();
      if(result.status == 200){
        this.memberDefault = result.data;
        this.radio = result.data.id;
        this.usernamer = result.data.name
        if (Object.keys(this.$route.query).length) {
          this.queryOrderList({
            order_state: this.$route.query.active,
            user_people_id: result.data.id,
            currentPage: this.currentPage
          });
        }else{
          this.queryOrderList({
            order_state: "",
            user_people_id: result.data.id,
            currentPage: this.currentPage
          });
        }
      }else{
        this.$toast(result.message)
      }
    },
    handleExchange(){
      this.memberArrList.length > 0 && (this.show = true)
    },
    handleConfirm(){
      this.show = false
      this.usernamer = this.memberArrList.length > 0 ? this.memberArrList.filter(item => item.id == this.radio)[0].name : this.memberDefault.username
      localStorage.setItem('usernamer', this.usernamer)
      this.queryOrderList({
        order_state: this.active,
        user_people_id: this.radio
      });
    },
    handleRadio(name){
      console.log(name,'handleRadio')
      this.radio = name
      localStorage.setItem('userId', name)
    },
    handleCancel(item, status) {
      this.$dialog
        .confirm({
          title: "提示",
          message: `${status == '7' ? '确定要取消订单吗?' : '完成订单'}`,
        })
        .then(async () => {
          let params = {
            id: item.order_id,
            order_status: status,
            currentPage: this.currentPage
          };
          let result = await ucenterOrderCancel(params, item.order_id);
          if (result.status == 200) {
            this.queryOrderList({
              order_state: this.active,
              user_people_id: this.radio,
              currentPage: this.currentPage
            });
          }
        })
        .catch(() => {
          // on cancel
        });
    },
    async queryMemberList() {
      let result = await memberList();
      if (result.status == 200) {
        this.memberArrList = result.data.model;
      } else {
        this.$toast(result.message);
      }
    },
    handleDetail(item) {
      this.$router.push({
        path: `/user/order/detail/${item.order_id}`,
      });
    },
    handleChange(e) {
      console.log(e, "changetab");
      let params = {
        order_status: this.tabList.filter((item) => item.value == e)[0].value,
        user_people_id: this.radio,
        currentPage: this.currentPage
      };
      this.queryOrderList(params);
    },
    handlePage(e) {
      this.currentPage = e;
      let params = {
        order_status: this.active,
        user_people_id: this.radio,
        currentPage: e
      };
      this.queryOrderList(params);
    },
    async queryOption() {
      let result = await ucenterOrderOption();
      if (result.status == 200) {
        let tabList = result.data.order_state;
        tabList.unshift({
          value: "",
          label: "全部",
        });
        this.tabList = tabList;
        this.stateList = result.data.pay_state;
      } else {
        this.$toast(result.message);
      }
    },
    async queryOrderList(params) {
      let result = await ucenterOrder(params);
      if (result.status == 200) {
        this.orderList = result.data.model;
        this.pageCount = result.data._meta.pageCount;
      }
    },
  },
};
</script>
<style lang='less'>
@import "~@/assets/less/mixin";
.order-container {
  // min-height: 100%;
  background: #f5f5f5;
  padding: 15px;
  .van-panel {
    margin-bottom: 12px;
  }
}
.min-wrapper{
  min-height: 100px;
  padding: 12px 15px;
  .van-radio{
    padding: 15px 0;
    border-bottom: 1px solid #f5f5f5;
    margin-bottom: 5px;
  }
}
.order-admin {
  // background: #f5f5f5;
  height: 100%;
  .switch-add {
    background: #edffeb;
    color: #4ece40;
    padding: 10px 15px;
    display: flex;
    justify-content: center;
    align-items: center;
    .van-button {
      margin-left: 10px;
      background: transparent;
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: auto;
    }
    .uname {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  .order-container {
    .order-product {
      padding: 15px;
      position: relative;
      display: -webkit-box;
      display: -webkit-flex;
      display: flex;
      -webkit-box-align: center;
      -webkit-align-items: center;
      align-items: center;
      justify-content: space-around;
    }

    .order-product-hd {
      margin-right: 0.8em;
      width: 70px;
      height: 70px;
      line-height: 70px;
      text-align: center;
    }

    .order-product-hd img {
      width: 100%;
      max-height: 100%;
      vertical-align: top;
      border-radius: 5px;
    }

    .order-product-bd {
      -webkit-box-flex: 1;
      -webkit-flex: 1;
      flex: 1;
      min-width: 0;
    }
    .price {
      font-size: 16px;
      color: #e02e2e;
    }
    .order-product-bd h2 {
      font-weight: 400;
      font-size: 14px;
      height: 44px;
      line-height: 1.5;
      color: #333;
      width: auto;
      word-wrap: normal;
      word-wrap: break-word;
      word-break: break-all;
      padding-bottom: 0.4rem;
      .ellipsisLine(2);
    }
  }
}
.van-cell {
  .van-cell__value {
    color: #999;
  }
}
.status-1 {
  .van-cell__value {
    color: #E02E2E;
  }
}
.status-3 {
  .van-cell__value {
    color: #E02E2E;
  }
}
.status-5 {
  .van-cell__value {
    color: #4ECE40;
  }
}
.status-7 {
  .van-cell__value {
    color: #333;
  }
}
.status-9 {
  .van-cell__value {
    color: #4ECE40;
  }
}
.status-12 {
  .van-cell__value {
    color: #4ECE40;
  }
}
.van-panel__footer {
  .van-button {
    margin-left: 10px;
  }
}
</style>